'use client'

import { useState, useMemo } from 'react'
import { products } from '@/data/products'
import ProductSearch from '@/components/ProductSearch'
import ProductCard from '@/components/ProductCard'

export default function ProductsPage() {
  const [searchQuery, setSearchQuery] = useState('')
  const [activeCategory, setActiveCategory] = useState('all')

  // 使用 useMemo 优化搜索性能
  const filteredProducts = useMemo(() => {
    let filtered = products

    // 应用分类过滤
    if (activeCategory !== 'all') {
      filtered = filtered.filter(product => product.category === activeCategory)
    }

    // 应用搜索过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter(product => {
        // 检查基本字段
        const basicMatch = 
          product.name.toLowerCase().includes(query) ||
          product.description.toLowerCase().includes(query) ||
          product.category.toLowerCase().includes(query)

        // 检查特点数组
        const featuresMatch = product.features?.some(feature => 
          feature.toLowerCase().includes(query)
        )

        // 检查规格对象的键和值
        const specificationsMatch = product.specifications && 
          Object.entries(product.specifications).some(([key, value]) => 
            key.toLowerCase().includes(query) || 
            value.toLowerCase().includes(query)
          )

        return basicMatch || featuresMatch || specificationsMatch
      })
    }

    return filtered
  }, [searchQuery, activeCategory])

  const handleSearch = (query: string) => {
    setSearchQuery(query)
  }

  const handleCategoryChange = (category: string) => {
    setActiveCategory(category)
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-16">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">产品中心</h1>
          <p className="text-gray-600 max-w-2xl mx-auto">
            我们提供优质的包装制品，包括胶合卡板、异型托盘、包装箱等，满足您的各种包装需求。
          </p>
        </div>
        
        {/* Search and Filter */}
        <div className="mb-12">
          <ProductSearch onSearch={handleSearch} onCategoryChange={handleCategoryChange} />
        </div>

        {/* Products Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {filteredProducts.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>

        {/* No Results */}
        {filteredProducts.length === 0 && (
          <div className="text-center py-16">
            <h3 className="text-xl text-gray-600">没有找到相关产品</h3>
            <p className="text-gray-500 mt-2">
              请尝试其他搜索关键词或重置筛选条件
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
